<?php
namespace App\Repositories;

use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;

class GoodNumberRepository
{
    /**
     * 靓号添加
     * @param array $param
     * @return mixed
     * @throws BasicException
     */
    public function goodNumberAdd(array $param)
    {
        $ip = $param['ip'];
        unset($param['ip']);
        $goodNumberObj = app('model_good_number')->create($param);
        if ($goodNumberObj) {
            // 插入一条数据到个性商城
            $data = [
                // 靓号类型商品
                'category_id' => 3,
                'title' => '靓号:' . $param['good_number'],
                'picture' => '',
                'special' => '',
                'add_time' => time(),
                'on_sale'  => 2
            ];
            $mallProduct = app('repo_mall')->mallProductsAdd($data);
            if(!empty($mallProduct)){
                // 靓号信息写入redis
                $expiredTime = $param['expired_time'] ? strtotime(date('Y-m-d H:i:00', $param['expired_time'])) : 0;
                app('redis')->hset('goodNumber', $param['good_number'], json_encode(['user_id'=>0,'cate_id'=>$param['cate_id'],'expired_time'=>$expiredTime]));
                // 管理员操作日志
                //$adminLogObj = app('model_admin_log')->create(['admin_id'=>$param['admin_id'],'client_ip'=>$ip,'dateline'=>time(),'uri'=>'/good_number/add','action_name'=>'GoodNumber','method_name'=>'GoodNumberAdd','content'=>'添加靓号']);
                //if ($adminLogObj) return $adminLogObj;
            }

            return;
        };


        throw new BasicException(97004);
    }

    /**
     * 靓号编辑
     * @param int $id
     * @param array $param
     * @return bool
     * @throws BasicException
     */
    public function goodNumberUpdate(int $id, array $param)
    {
        // 是否下发过通知消息  false:否  true:是   如果已经发过 不要重复发
        $sendMsgFlag = false;
        // 获取用户信息
        $userDetail = app('repo_user_data')->getUserInfoByUserCode($param['user_code']);
        if (!empty($userDetail['good_number'])) {
            $userDetail['good_number'] = $userDetail['good_number']['good_number'];
        } else {
            $userDetail['good_number'] = 0;
        }
        if (empty($userDetail)) throw new BasicException(70008);
        // 获取靓号信息
        $goodNumber = $this->getGoodNumberInfoById($id);
        if (!empty($goodNumber['user_data'])) {
            $goodNumber['user_code'] = $goodNumber['user_data']['user_code'];
            $goodNumber['last_user_code'] = $goodNumber['user_data']['last_user_code'];
            unset($goodNumber['user_data']);
        } else {
            $goodNumber['user_code'] = $goodNumber['last_user_code'] = 0;
        }
        $goodNumber['good_number_cate_name'] = $goodNumber['good_number_cate']['name'];
        unset($goodNumber['good_number_cate']);
        $redis = app('redis');
        $userDataRepo = app('repo_user_data');
        $userNewsRepo = app('repo_user_news');
        // 如果靓号已经存在其他用户而且不是自己
        if ($goodNumber['user_id'] && $goodNumber['user_id']!=$userDetail['user_id']) {
            // 给原来用户的编号变化插入一条日志
            $userChangeData = ['user_id'=>$goodNumber['user_id'],'change_from'=>$goodNumber['user_code'],'change_to'=>$goodNumber['last_user_code'],'type'=>1,'add_time'=>time()];
            $this->userChangeAdd($userChangeData);
            // 给靓号之前的用户推送一条收回靓号通知
            $userNewsData = [
                'user_id' => $goodNumber['user_id'],
                'content' => '尊敬的用户，您目前使用的靓号'.$goodNumber['good_number'].'已被提前收回，如有异议，请联系官方客服。',
                'add_time' => time(),
                'status' => 0,
                'title' => '靓号通知',
            ];
            $userNewsRepo->userNewsAdd($userNewsData);
            $userDataRepo->resetUserCode($goodNumber['user_id']);
        }

        // 如果当前用户拥有除此之外的其他靓号 则把之前靓号置空 再将新靓号制定为当前用户
        if ($userDetail['good_number'] && $userDetail['good_number']!=$goodNumber['good_number']) {
            $this->goodNumberEdit($userDetail['good_number'], ['user_id'=>0,'expired_time'=>0,'head_img'=>'','nickname'=>'']);
            if ($redis->hexists('goodNumber',$userDetail['good_number'])) {
                $tempData = json_decode ( $redis->hget('goodNumber',$userDetail['good_number'] ),true);
                $tempData['user_id'] = 0;
                $redis->hset('goodNumber',$userDetail['good_number'] ,json_encode($tempData));
            }
            $sendMsgFlag = true;
            $userNewsData = [
                'user_id' => $userDetail['user_id'],
                'content' => '尊敬的用户，您目前使用的靓号由'.$userDetail['good_number'].'更改为'.$goodNumber['good_number'].'，如有异议，请联系官方客服。',
                'add_time' => time(),
                'status' => 0,
                'title' => '靓号通知',
            ];
            $userNewsRepo->userNewsAdd($userNewsData);
            // 插入一条管理员操作日志 todo...
        }

        // 修改靓号最新拥有者user_code为靓号
        if ($goodNumber['user_id'] != $userDetail['user_id']) {
            $userDataRepo->goodNumber2UserCode($userDetail['user_id'], $goodNumber['good_number']);
            $userChangeData = ['user_id'=>$userDetail['user_id'],'change_from'=>$userDetail['user_code'],'change_to'=>$goodNumber['good_number'],'type'=>1,'add_time'=>time()];
            $this->userChangeAdd($userChangeData);
        }

        $expiredStr = empty($param['expired_time']) ? '永久' : date('Y-m-d H:i:s');
        // 靓号原属用户和当前用户不同时 且之前没有推送过其他更改靓号通知时 才推送此消息
        if ($goodNumber['user_id'] != $userDetail['user_id']) {
            if (!$sendMsgFlag) {
                $userNewsData = [
                    'user_id' => $userDetail['user_id'],
                    'content' => '尊敬的用户，您通过【'.$goodNumber['good_number_cate_name'].'】获得号段为'.$goodNumber['good_number'].'的靓号，有效期限为'.$expiredStr.'，祝您使用愉快，天天开心。',
                    'add_time' => time(),
                    'status' => 0,
                    'title' => '靓号通知',
                ];
                $userNewsRepo->userNewsAdd($userNewsData);
                $sendMsgFlag = true;
            }
            // 插入一条管理员操作日志 todo...
        } else if ($param['expired_time'] != $goodNumber['expired_time']) {
            if ($param['expired_time'] == 0) {
                $msg = ' 恭喜~恭喜~  尊敬的用户,您为'.$goodNumber['good_number'].'的靓号使用权限，由固定时限延长至永久使用了哦，【鼓掌】有没有很开心呀？快去和小伙伴们分享这个好消息吧。';
                $str = '使用的靓号由固定时限延长至永久';
            } else {
                if ($goodNumber['expired_time'] && $param['expired_time']>$goodNumber['expired_time']) {
                    $msg = ' 恭喜~恭喜~  尊敬的用户：您为'.$goodNumber['good_number'].'的靓号使用权限，由'.date('Y-m-d H:i',$goodNumber['expired_time']).' 更改为'.$expiredStr.'，如有疑问，请联系官方客服';
                } else if ($goodNumber['expired_time'] && $param['expired_time']<$goodNumber['expired_time']) {
                    $msg = ' 尊敬的用户：您为'.$goodNumber['good_number'].'的靓号使用权限，由'.date('Y-m-d H:i',$goodNumber['expired_time']).' 更改为'.$expiredStr.'，如有疑问，请联系官方客服';
                } else if (!$goodNumber['expired_time']) {
                    $msg = ' 尊敬的用户：您为'.$goodNumber['good_number'].'的靓号使用权限，由永久使用更改为'.$expiredStr.'，如有疑问，请联系官方客服';
                }
                $str = '使用的靓号由永久修改为固定时间';
            }
            $userNewsData = [
                'user_id' => $userDetail['user_id'],
                'content' => $msg,
                'add_time' => time(),
                'status' => 0,
                'title' => '靓号通知',
            ];
            $userNewsRepo->userNewsAdd($userNewsData);
            $sendMsgFlag = true;
            // 插入一条管理员操作日志 todo...
        }

        // 记录到靓号表
        unset($param['ip'],$param['user_code']);
        // 如果靓号存在用户 不修改cate_id
        if ($goodNumber['user_id']) {
            $cateId = $param['cate_id'];
            unset($param['cate_id']);
        }
        $param['user_id'] = $userDetail['user_id'];
        $param['nickname'] = $userDetail['nickname'];
        $param['head_img'] = $userDetail['head_picture'];
        $this->goodNumberEdit($goodNumber['good_number'], $param);

        if ($redis->hexists('goodNumber',$goodNumber['good_number'])){
            $tempData = json_decode($redis->hget('goodNumber',$goodNumber['good_number'] ),true);
            $tempData['user_id'] = $userDetail['user_id'];
            $tempData['cate_id'] = $cateId;
            $tempData['expired_time'] = $param['expired_time'] ? strtotime(date('Y-m-d H:i:00',$param['expired_time'])) : 0;
            $redis->hset('goodNumber', $goodNumber['good_number'] ,json_encode ($tempData));
        }
        // 插入一条管理员操作日志 todo...
        return true;
    }

    /**
     * 靓号编辑
     * @param int $goodNumber
     * @param array $param
     * @return mixed
     * @throws BasicException
     */
    public function goodNumberEdit(int $goodNumber, array $param)
    {
        $res = app('model_good_number')
            ->where('good_number', $goodNumber)
            ->update($param);
        if ($res) return $res;
        throw new BasicException(97009);
    }

    /**
     * 修改记录添加
     * @param array $param
     * @return mixed
     * @throws BasicException
     */
    public function userChangeAdd(array $param)
    {
        $userChangeObj = app('model_user_change')->create($param);
        if ($userChangeObj) return $userChangeObj;
        throw new BasicException(97007);
    }

    /**
     * 通过ID获取靓号信息
     * @param int $id
     * @return mixed
     */
    public function getGoodNumberInfoById(int $id)
    {
        return app('model_good_number')->where('id', $id)->select('id','user_id','cate_id','nickname','good_number','expired_time','remark')
            ->withOnly('user_data',['user_id','last_user_code','user_code'])
            ->withOnly('good_number_cate',['id','name'])
            ->first()->toArray();
    }

    /**
     * 靓号详情
     * @param int $id
     * @return mixed
     */
    public function goodNumberDetail(int $id)
    {
        $detail = app('model_good_number')->where('id', $id)->select('id','user_id','cate_id','expired_time','remark')
            ->withOnly('user_data',['user_id','last_user_code','user_code'])
            ->first()->toArray();
        $cateList = $this->getGoodNumberCateList()->toArray();
        $detail['last_user_code'] = !empty($detail['user_data']) ? $detail['user_data']['last_user_code'] : 0;
        $detail['cate_list'] = $cateList;
        unset($detail['user_data']);
        return $detail;
    }

    /**
     * 靓号删除
     * @param array $param
     * @return bool
     * @throws BasicException
     */
    public function goodNumberDelete(array $param)
    {
        $goodNumberList = app('model_good_number')->select('id','user_id','good_number')->whereIn('id', $param['ids'])->get();
        $usingGoodNumberIds = $nusingGoodNumberIds = $usingUserIds = [];
        foreach ($goodNumberList as $value) {
            if ($value->user_id) {
                $usingUserIds[] = $value->user_id;
                $usingGoodNumberIds[] = $value->id;
            } else {
                $nusingGoodNumberIds[] = $value->id;
            }
        }
        $redis = app('redis');
        if ($usingUserIds) {
            DB::statement('UPDATE ln_user_data set user_code = last_user_code where user_id  in(' . implode(',', $usingUserIds) . ')');
            $userNewsData = [];
            foreach ($goodNumberList as $value) {
                if ($value->user_id) {
                    $userNewsData[] = [
                        'user_id' => $value->user_id,
                        'content' => '尊敬的用户：您目前使用的靓号' . $value->good_number . '已被提前收回，如有异议，请联系官方客服。',
                        'add_time' => time(),
                        'status' => 0,
                        'title' => '靓号通知',
                    ];
                    if ($redis->hexists('goodNumber', $value->good_number)) {
                        $tempData = json_decode($redis->hget('goodNumber',$value->good_number),1 );
                        $tempData['user_id'] = $tempData['expired_time'] = 0;
                        $redis->hset('goodNumber', $value->good_number, json_encode($tempData));
                    }
                }
            }
            DB::table('ln_user_news')->insert($userNewsData);
            app('model_good_number')->whereIn('id', $usingGoodNumberIds)->update(['user_id'=>0,'nickname'=>'','head_img'=>'','admin_id'=>$param['admin_id'],'admin_name'=>$param['admin_name']]);
        }
        if ($nusingGoodNumberIds) {
            foreach ($goodNumberList as $value) {
                if ($redis->hexists('goodNumber',$value->good_number)) {
                    $redis->hdel('goodNumber',$value->good_number);
                }
            }
            app('model_good_number')->whereIn('id', $nusingGoodNumberIds)->delete();

        }
        return true;
        throw new BasicException(97006);
    }

    /**
     * 靓号列表
     * @param array $param
     * @param int $page
     * @param int $perPage
     * @return mixed
     */
    public function goodNumberList(array $param, int $page=1, int $perPage=10)
    {
        $list = app('model_good_number')->select('id','good_number','user_id','expired_time','cate_id','admin_id','add_time','remark');
        if (isset($param['good_number'])) $list = $list->where('good_number', $param['good_number']);
        if (isset($param['cate_id'])) $list = $list->where('cate_id', $param['cate_id']);
        if (isset($param['add_time'])) {
            $time = strtotime(date('Y-m-d', strtotime($param['add_time'])));
            $list = $list->whereBetween('add_time', [$time, $time+86399]);
        }
        $list = $list->withOnly('good_number_cate', ['id','name'])->withOnly('user_data', ['user_id','last_user_code','nickname'])
            ->withOnly('admin', ['admin_id','admin_name'])->orderBy('id', $param['order']??'desc')->paginate($perPage, ['*'], '', $page);

        foreach($list as &$value) {
            $value->add_time = date('Y-m-d H:i:s', $value->add_time);
            $value->cate_name = $value->good_number_cate->name ?? '';
            if (!empty($value->user_data)) {
                $value->nickname = $value->user_data->nickname;
                $value->user_code = $value->user_data->last_user_code;
            } else {
                $value->nickname = $value->user_code = '';
            }
            if (!empty($value->admin)) {
                $value->admin_id = $value->admin->admin_id;
                $value->admin_name = $value->admin->admin_name;
            } else {
                $value->admin_id = $value->admin_name = '';
            }
            $value->status = $value->user_id ? 1 : 0;
            $value->expired_time = $value->expired_time==0 ?  0  : date('Y-m-d H:i:s');

            unset($value->good_number_cate,$value->user_data,$value->admin);
        }
        return $list;
    }

    /**
     * 查看已经存在该靓号
     * @param int $number
     * @return bool
     */
    public function isExistGoodNumber(int $number): bool
    {
        return app('model_good_number')->where('good_number', $number)->exists();
    }

    /**
     * 查看是否存在靓号分类
     * @param int $cateId
     * @return bool
     */
    public function isExistGoodNumberCate(int $cateId): bool
    {
        return app('model_good_number_cate')->where('id', $cateId)->exists();
    }

    /**
     * 靓号分类添加
     * @param $param
     * @return mixed
     * @throws BasicException
     */
    public function goodNumberCateAdd($param)
    {
        $goodNumberCate = app('model_good_number_cate')->create($param);
        if($goodNumberCate) return $goodNumberCate;
        throw new BasicException(97001);
    }

    /**
     * 靓号分类编辑
     * @param int $id
     * @param array $param
     * @return bool
     * @throws BasicException
     */
    public function goodNumberCateUpdate(int $id,array $param)
    {
        $goodNumberCate = app('model_good_number_cate')->where('id', $id)->first();
        if (empty($goodNumberCate)) throw new BasicException(70001);

        if (!empty($param['name'])||$param['name']==='0') $goodNumberCate->name = $param['name'];

        $res = $goodNumberCate->save();
        if ($res) return true;
        throw new BasicException(97002);
    }

    /**
     * 靓号分类删除
     * @param array $ids
     * @return mixed
     * @throws BasicException
     */
    public function goodNumberCateDelete(array $ids)
    {
        $res = app('model_good_number_cate')->whereIn('id',$ids)->delete();
        if($res) return $res;
        throw new BasicException(97003);
    }
    /**
     * 靓号分类列表
     * @param int $page
     * @param int $perPage
     * @return mixed
     */
    public function goodNumberCateList(int $page=1,int $perPage=10)
    {
        $list = app('model_good_number_cate')->paginate($perPage, ['*'], '', $page);
        foreach($list as &$value) {
            $value['add_time'] = date('Y-m-d H:i:s', $value->add_time);
        }
        return $list;
    }

    /**
     * 获取靓号分类列表
     * @return mixed
     */
    public function getGoodNumberCateList()
    {
        return app('model_good_number_cate')->select('id','name')->get();
    }
}


?>